package com.gpframework.module.wages.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.exception.CustomException;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.module.wages.domain.GzAttendanceManagement;
import com.gpframework.module.wages.domain.GzPersonnelFoundation;
import com.gpframework.module.wages.domain.req.GzAttendanceManagementUpdate;
import com.gpframework.module.wages.domain.vo.GzAttendanceManagementVo;
import com.gpframework.module.wages.mapper.GzAttendanceManagementMapper;
import com.gpframework.module.wages.service.IGzAttendanceManagementService;
import com.gpframework.module.wages.service.IGzPersonnelFoundationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
 * @ClassName GzAttendanceManagement
 * @Author gpframework
 * @Date 2024-01-19
 * @Version 1.0.0
 * @Description 考勤管理Service业务层处理
 */
@Service
public class GzAttendanceManagementServiceImpl extends ServiceImpl<GzAttendanceManagementMapper, GzAttendanceManagement> implements IGzAttendanceManagementService {

    @Autowired
    private  IGzPersonnelFoundationService iGzPersonnelFoundationService;
    @Autowired
    private  IGzAttendanceManagementService iGzAttendanceManagementService;

    /**
     * @Description 查询列表返回VO 用于返回给前端的列表接口
     * @Author gpframework
     * @Date 2024-01-19
     * @Param [lqw]
     * @Return List<GzAttendanceManagementVo>
     */
    @Override
    public List<GzAttendanceManagementVo> listVo(QueryWrapper<GzAttendanceManagement> lqw) {
        return this.baseMapper.listVo(lqw);
    }

    @Override
    public List<GzAttendanceManagementVo> listVoed(QueryWrapper<GzAttendanceManagement> lqw) {
        return this.baseMapper.listVoed(lqw);
    }

    /**
     * @Description 通过查询详情VO 用于返回给前端的列详情接口
     * @Author gpframework
     * @Date 2024-01-19
     * @Param [id]
     * @Return GzAttendanceManagementVo
     */
    @Override
    public GzAttendanceManagementVo getVoById(Long id) {
        return this.baseMapper.getVo(id);
    }

    @Override
    public void deleteByMonth(Date yearMonth) {
        this.baseMapper.delelteMonth(yearMonth);
    }

    @Override
    public boolean edit(List<GzAttendanceManagementUpdate> list) {
        ArrayList<GzAttendanceManagement> updateList = new ArrayList<>();
        for (GzAttendanceManagementUpdate gzAttendanceManagementUpdate : list) {
            GzAttendanceManagement gzAttendanceManagement = Convert.convert(new TypeReference<GzAttendanceManagement>() {}, gzAttendanceManagementUpdate);
            if (gzAttendanceManagement.getRequireDateNdancedays()!=null){
                //计算缺勤天数
                gzAttendanceManagement.setAbsenceDays(BigDecimal.valueOf(gzAttendanceManagement.getRequireDateNdancedays()- gzAttendanceManagement.getAttendanceDays()));
            }

            updateList.add(gzAttendanceManagement);
        }

        return this.updateBatchById(updateList);
    }

    @Override
    public String importListNote(List<GzAttendanceManagementVo> excelList, boolean updateSupport) {
        if (StringUtils.isNull(excelList) || excelList.size() == 0) {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (GzAttendanceManagementVo gzAttendanceManagementVo : excelList) {
            try {
                //查询数据
                GzAttendanceManagement attendanceManagement = iGzAttendanceManagementService.getOne(new QueryWrapper<GzAttendanceManagement>()
                        .eq("name", gzAttendanceManagementVo.getName())
                        .eq("department_name", gzAttendanceManagementVo.getDepartmentName())
                        .eq("month", gzAttendanceManagementVo.getMonth())
                        .eq("del_status", YesNoEnum.NO.getKey()));
                if (StringUtils.isNull(attendanceManagement)){
                    //新增考勤
                    GzAttendanceManagement gzAttendanceManagement = Convert.convert(new TypeReference<GzAttendanceManagement>() {}, gzAttendanceManagementVo);

                    // 创建Calendar对象
                    Calendar calendar = Calendar.getInstance();
                    //复制userId
                    //复制月度天数 应出勤天数 休息日
                    GzPersonnelFoundation gzPersonnelFoundation = iGzPersonnelFoundationService.getOne(new QueryWrapper<GzPersonnelFoundation>()
                            .eq("name", gzAttendanceManagementVo.getName())
                            .eq("department_name", gzAttendanceManagementVo.getDepartmentName())
                            .eq("del_status", YesNoEnum.NO.getKey()));

                    gzAttendanceManagement.setUserId(gzPersonnelFoundation.getId());
                    int month = gzAttendanceManagementVo.getMonth().getMonth();
                    calendar.set(Calendar.MONTH, month);
                    // 获取当前月份的天数
                    int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                    //月度天数
                    gzAttendanceManagement.setMonthlyDays(Double.valueOf(daysInMonth));
                    gzAttendanceManagement.setRequireDateNdancedays((daysInMonth-gzPersonnelFoundation.getMonthlyDays()));
                    gzAttendanceManagement.setRestDays(gzPersonnelFoundation.getMonthlyDays());
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、姓名 " + gzAttendanceManagement.getName() + " 导入成功");
                    iGzAttendanceManagementService.save(gzAttendanceManagement);
                } else if (updateSupport) {
                    //更新考勤
                    GzAttendanceManagement gzAttendanceManagement = Convert.convert(new TypeReference<GzAttendanceManagement>() {}, gzAttendanceManagementVo);

                    GzAttendanceManagement management = iGzAttendanceManagementService.getOne(new QueryWrapper<GzAttendanceManagement>()
                            .eq("name", gzAttendanceManagementVo.getName())
                            .eq("department_name", gzAttendanceManagementVo.getDepartmentName())
                            .eq("month", gzAttendanceManagementVo.getMonth())
                            .eq("del_status", YesNoEnum.NO.getKey()));
                    if (management!=null){
                        //获取ID
                        gzAttendanceManagement.setId(management.getId());
                    }

                    // 创建Calendar对象
                    Calendar calendar = Calendar.getInstance();
                    //复制userId
                    //复制月度天数 应出勤天数 休息日
                    GzPersonnelFoundation gzPersonnelFoundation = iGzPersonnelFoundationService.getOne(new QueryWrapper<GzPersonnelFoundation>()
                            .eq("name", gzAttendanceManagementVo.getName())
                            .eq("department_name", gzAttendanceManagementVo.getDepartmentName())
                            .eq("del_status", YesNoEnum.NO.getKey()));

                    gzAttendanceManagement.setUserId(gzPersonnelFoundation.getId());
                    int month = gzAttendanceManagementVo.getMonth().getMonth();
                    calendar.set(Calendar.MONTH, month);
                    // 获取当前月份的天数
                    int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                    //月度天数
                    gzAttendanceManagement.setMonthlyDays(Double.valueOf(daysInMonth));
                    gzAttendanceManagement.setRequireDateNdancedays((daysInMonth-gzPersonnelFoundation.getMonthlyDays()));
                    gzAttendanceManagement.setRestDays(gzPersonnelFoundation.getMonthlyDays());
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、姓名 " + gzAttendanceManagement.getName() + " 更新成功");
                    iGzAttendanceManagementService.updateById(gzAttendanceManagement);
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、姓名 " + gzAttendanceManagementVo.getName() + " 已存在");
                }

            }catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、姓名 " + gzAttendanceManagementVo.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }

        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }


}
